package cn.itsource.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.itsource.domain.OssPropertites;
import cn.itsource.service.FileService;

import com.alibaba.druid.wall.violation.ErrorCode;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;


@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private OssPropertites ossPropertites;
    @Override
    public String fileUpload(MultipartFile multipartFile) {
        ArrayList<String> strings = new ArrayList<>();
        strings.add("image/png");
        strings.add("image/gif");
        strings.add("image/jpeg");
        if (strings.contains(multipartFile.getContentType())){

                //获取文件名
                String fileName = multipartFile.getOriginalFilename();
                //获取文件类型
                String fileType = fileName.substring(fileName.lastIndexOf("."));
                //uuid
                String uuid = IdUtil.fastSimpleUUID();
                String realName = "pethome-cloud/" + uuid + fileType;
                OSS build = new OSSClientBuilder().build(ossPropertites.getEndpoint(), ossPropertites.getAccessKey(), ossPropertites.getSecretKey());
            PutObjectRequest putObjectRequest = null;
            try {
                putObjectRequest = new PutObjectRequest(ossPropertites.getBucketName(), realName, multipartFile.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
            build.putObject(putObjectRequest);
                build.shutdown();//关闭OSSClient
                String imagePath = "https://" + ossPropertites.getBucketName()+"."+ossPropertites.getEndpoint()+"/"+realName;

                return imagePath;

        }else {
            //文件格式错误，非jpg/png/gif
            throw new RuntimeException("文件格式有误,非jpg/png/gif");
        }

    }
}
